package com.morimoto.healthmeter.graph;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import com.morimoto.healthmeter.HealthMeterActivity;
import com.morimoto.healthmeter.R;
import com.morimoto.rmlib.DrawElement;
import com.morimoto.rmlib.StorageManager;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class GraphLayout extends LinearLayout {
	
	private static final int GRAPH_WEIGHT = 0;
	private static final int GRAPH_FAT	= 1;
	private static final int GRAPH_USER   = 2;
	
	private static final String[] GRAPG_LABEL = {"体重の推移", "体脂肪率の推移", "その他のデータの推移"};

	private static final int TIME_SPAN_1_WEEK  = 0;
	private static final int TIME_SPAN_1_MONTH = 1;
	private static final int TIME_SPAN_3_MONTH = 2;
	private static final int TIME_SPAN_6_MONTH = 3;
	private static final int TIME_SPAN_1_YEAR  = 4;
	private static final int TIME_SPAN_3_YEAR  = 5;
	private static final int TIME_SPAN_5_YEAR  = 6;
	private static final int TIME_SPAN_10_YEAR = 7;
	
	private static final int[] GRID_NUM = new int[] {7, 10, 9, 12, 12, 9, 10, 10};
	
	private HealthMeterActivity mMain = null;
	private Context mContext = null;
	
	private int mGraphIndex = 0;
	private int mTimeSpanIndex = 0;
	
	private FrameLayout mGraphLayout = null;
	private GraphicalView mLineChartView = null;
	
	public GraphLayout(final Context context) {
		super(context);
		mContext = context;
		mMain = (HealthMeterActivity) context;
		setOrientation(LinearLayout.VERTICAL);

		LinearLayout spinerInLayout = new LinearLayout(context);
		spinerInLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		spinerInLayout.setOrientation(LinearLayout.HORIZONTAL);

		HealthMeterActivity main = (HealthMeterActivity) context;
		StorageManager sm = main.getStorage();
		int dataNum = sm.getInt("dataNum");
		if (dataNum < 1) {
			setGravity(Gravity.CENTER);
			TextView tv = new TextView(context);
			tv.setText("表示するデータがありません");
			addView(tv);
			return;
		}
		
		// Spinner for graph spec
		Spinner spinner = new Spinner(context);
		spinner.setLayoutParams(new LayoutParams((int) (mMain.getScreenWidth() * 0.5f), LayoutParams.WRAP_CONTENT));
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("体重グラフ");
		adapter.add("体脂肪グラフ");
		adapter.add("その他のデータグラフ");
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mGraphIndex = position;
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		spinerInLayout.addView(spinner);

		// Spinner for time span
		Spinner spinner2 = new Spinner(context);
		spinner2.setLayoutParams(new LayoutParams((int) (mMain.getScreenWidth() * 0.5f), LayoutParams.WRAP_CONTENT));
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter2.add("1 week");
		adapter2.add("1 month");
		adapter2.add("3 month");
		adapter2.add("6 month");
		adapter2.add("1 year");
		adapter2.add("3 year");
		adapter2.add("5 year");
		adapter2.add("10 year");
		spinner2.setAdapter(adapter2);
		spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mTimeSpanIndex = position;
				mGraphLayout.removeAllViews();
				mLineChartView.destroyDrawingCache();
				mLineChartView = null;
				mLineChartView = new LineChart().getChartView(mContext);
				mGraphLayout.addView(mLineChartView);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		spinerInLayout.addView(spinner2);
		addView(spinerInLayout);

		mGraphLayout = new FrameLayout(context);
		mGraphLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		//GraphViewの生成
		mLineChartView = new LineChart().getChartView(context);
		if (mLineChartView != null) {
			mGraphLayout.addView(mLineChartView);
		}
		
//		mGraphView = new FishView(context);
//		graphLayout.addView(mGraphView);
		
		addView(mGraphLayout);
	}


}

class GraphElement {
	
	String graphLabel;
	
	int gridNum;
	
	Date[] dateArray;
	
	float[] valueArray;
}


class LineChart extends AbstractChart {
	
	private GraphElement mGraphElem = null;

	public LineChart() {
		super();
	}
	
	public void init(GraphElement ge) {
		
	}

	public GraphicalView getChartView(Context context) {
		
		String[] titles = new String[] { "weight" };
		List<Date[]> dates = new ArrayList<Date[]>();
		List<double[]> values = new ArrayList<double[]>();
		
		HealthMeterActivity main = (HealthMeterActivity) context;
		StorageManager sm = main.getStorage();
		
		int dataNum = sm.getInt("dataNum");
		
		if (dataNum < 1) {
			return null;
		}
		
		Date[] dateArray = new Date[dataNum];
		double[] valueArray = new double[dataNum];
		
		for (int i = 0; i < dataNum; i++) {
			valueArray[i] = sm.getFloat(i + "_w");
			String date = sm.getString(i + "_d");
			String[] localDateArray = date.split("_");
			int year = Integer.valueOf(localDateArray[0]);
			int month = Integer.valueOf(localDateArray[1]);
			int day = Integer.valueOf(localDateArray[2]);
			dateArray[i] = new Date(year - 1900, month, day);
		}
		
//			new Date[] { new Date(95, 0, 1), new Date(95, 3, 1), new Date(95, 6, 1),
//				new Date(92, 9, 1), new Date(96, 0, 1), new Date(96, 3, 1), new Date(96, 6, 1),
//				new Date(96, 9, 1), new Date(97, 0, 1), new Date(97, 3, 1), new Date(97, 6, 1),
//				new Date(97, 9, 1), new Date(98, 0, 1), new Date(98, 3, 1), new Date(98, 6, 1),
//				new Date(98, 9, 1), new Date(99, 0, 1), new Date(99, 3, 1), new Date(99, 6, 1),
//				new Date(99, 9, 1), new Date(100, 0, 1), new Date(100, 3, 1), new Date(100, 6, 1),
//				new Date(100, 9, 1), new Date(100, 11, 1)};
//		dateValues.
		dates.add(dateArray);

		values.add(valueArray);
//		new double[] { 4.9, 5.3, 3.2, 4.5, 6.5, 4.7, 5.8, 4.3, 4, 2.3, -0.5, -2.9, 3.2, 5.5,
//			4.6, 9.4, 4.3, 1.2, 0, 0.4, 4.5, 3.4, 4.5, 4.3, 4 };
		int[] colors = new int[] { Color.rgb(255, 190, 255) };
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		setChartSettings(renderer, "Weekly chart", "Date", "kg", dateArray[dateArray.length - 1].getTime() - 604800000,
			dateArray[dateArray.length - 1].getTime(), valueArray[valueArray.length - 1] - 3.0f, valueArray[valueArray.length - 1] + 3.0f, Color.GRAY, Color.LTGRAY);
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
		}
		renderer.setYLabels(10);
		GraphicalView view = ChartFactory.getTimeChartView(context, buildDateDataset(titles, dates, values),
			renderer, "yy/MM/dd");
		
		
//		String[] titles = new String[] { "Weight" };
//		List<double[]> x = new ArrayList<double[]>();
//		for (int i = 0; i < titles.length; i++) {
//			x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
//		}
//		List<double[]> values = new ArrayList<double[]>();
//		values.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, 13.9 });
//		int[] colors = new int[] { Color.CYAN } ;
//		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE };
//		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
//		int length = renderer.getSeriesRendererCount();
//		for (int i = 0; i < length; i++) {
//			((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
//		}
//		setChartSettings(renderer, "体重の推移", "Day", "Weight", 1, GRID_NUM[mTimeSpanIndex], 0, 40, Color.LTGRAY, Color.LTGRAY);
//		renderer.setXLabels(12);
//		renderer.setYLabels(10);
//		renderer.setShowGrid(true);
//		renderer.setXLabelsAlign(Align.RIGHT);
//		
//		renderer.setYLabelsAlign(Align.RIGHT);
//		renderer.setZoomButtonsVisible(true);
//		renderer.setPanLimits(new double[] { -GRID_NUM[mTimeSpanIndex], GRID_NUM[mTimeSpanIndex], 0, 40 });
//		renderer.setZoomLimits(new double[] { 0, 12, 0, 40 });
//
//		GraphicalView view = ChartFactory.getLineChartView(context, buildDataset(titles, x, values), renderer);
		return view;
	}

}
class FishView extends View implements OnGestureListener {
	
	private GestureDetector mGestureDetector = null;

//	private Handler mHandler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			super.handleMessage(msg);
//		}
//	};

	private DrawElement mObj1 = new DrawElement();

	public FishView(Context context) {
		super(context);
		
		mGestureDetector = new GestureDetector(this);
		
		mObj1.init(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher), 0, 0, 100, 100);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		mObj1.draw(canvas);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mGestureDetector.onTouchEvent(event);
		return true;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return true;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		mObj1.postCenterXY(-distanceX, -distanceY);
		invalidate();
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return true;
	}
	
}